package com.rchat.pocmini;

import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothProfile;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.AudioManager;
import android.support.multidex.MultiDex;
import android.text.TextUtils;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.aso.common.encrypt.EncryptUtils;
import com.aso.common.global.CommonGlobal;
import com.aso.common.http.utils.HttpUtils;
import com.aso.common.utils.FileUtils;
import com.aso.common.utils.Utils;
import com.baidu.mapapi.SDKInitializer;
import com.itsdf07.alog.ALog;
import com.itsdf07.alog.ALogLevel;
import com.rchat.pocmini.global.AppGlobal;
import com.rchat.pocmini.receiver.NetworkReceiver;
import com.rchat.pocmini.session.PocAirtalkeeSessionManager;
import com.rchat.pocmini.util.AppConfig;
import com.rchat.pocmini.util.NetworkUtil;
import com.rchat.pocmini.util.SPUtil;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.analytics.MobclickAgent;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by ljd on 2017/3/9.
 */

public class PocApplication extends Application implements NetworkReceiver.NetworkChangeListener {

    private static final String TAG = "PocApplication";
    private static PocApplication instance;
    private static Context mContext;
    private BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    public AudioManager mAudioManager;
    /**
     * Release：true
     * Debug：false
     * 编正式包的时候，该字段需要改成true
     */
    private boolean isRelease = true;

    @Override
    public void onCreate() {
        super.onCreate();
//        if (ALog.ISLOG){
//            if (LeakCanary.isInAnalyzerProcess(this)) {
//                // This process is dedicated to LeakCanary for heap analysis.
//                // You should not init your app in this process.
//                return;
//            }
//            LeakCanary.install(this);
//            // Normal app init code...
//        }
        initFirst();
        initCrashReport2Bugly();

        SDKInitializer.initialize(getApplicationContext());
        mAudioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        mContext = this;
        instance = this;

        //TODO 这块后续要放在ALog的init中去处理
//        ALog.ISLOG = (Boolean) SPUtil.get(this, AppGlobal.KEY_SP_ISLOG, false);

        //Airtalkee sdk init
        initAirtalkee();
        //Jpush
        JPushInterface.setDebugMode(ALog.isLog());
        JPushInterface.init(getApplicationContext());
        Utils.init(this);
        HttpUtils.getInstance();
        EncryptUtils.getInstance().init(this);

        //友盟,普通统计类型
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_NORMAL);
        //禁止禁止默认的页面统计方式，使用自定义的统计方式
        MobclickAgent.openActivityDurationTrack(false);
        /**
         * 如果enable为true，SDK会对日志进行加密。加密模式可以有效防止网络攻击，提高数据安全性。
         * 如果enable为false，SDK将按照非加密的方式来传输日志。
         * 如果您没有设置加密模式，SDK的加密模式为false（不加密）。
         */
        MobclickAgent.enableEncrypt(true);//6.0.0版本以后
        MobclickAgent.setDebugMode(ALog.isLog());

        //======= 设置心跳 ======//
        if (NetworkUtil.isNetworkConnected(this)) {
            switch (NetworkUtil.getNetworkType(this)) {
                case NetworkUtil.NETWORK_INVALID:
                    break;
                case NetworkUtil.NETWORK_WIFI:
                    PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().setHeartBeat(5, 0);//设置心跳
                    break;
                case NetworkUtil.NETWORK_2G:
                    PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().setHeartBeat(5, 0);//设置心跳
                    break;
                case NetworkUtil.NETWORK_3G:
                    PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().setHeartBeat(5, 0);//设置心跳
                    break;
                case NetworkUtil.NETWORK_4G:
                    PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().setHeartBeat(30, 0);//设置心跳
                    break;
            }
        }
    }


    /**
     * 启动时就需要优先初始化的事情
     */
    private void initFirst() {
        initCommonGlobal();
        ALog.init()
                .setTag(CommonGlobal.TAG_DEFAULT)
                .setLogLevel(CommonGlobal.ISLOG? ALogLevel.FULL:ALogLevel.NONE)
                .setLog2Local(CommonGlobal.ISLOG2LOCAL);
    }

    /**
     * 初始化Common模块中CommonGlobal的默认属性
     */
    private void initCommonGlobal() {
        CommonGlobal.TAG_DEFAULT = AppGlobal.TAG_DEFAULT;
        CommonGlobal.BASE_PATH = AppGlobal.BASE_PATH;
        CommonGlobal.ISLOG = (boolean) SPUtil.get(getApplicationContext(), AppGlobal.KeySP.KEY_SP_ISLOG, false);
    }


    /**
     * Bugly平台崩溃上报
     * 平台是苏登福申请的，有问题请找他，他可能要找你收费哦~~~~
     */
    private void initCrashReport2Bugly() {
        com.itsdf07.alog.ALog.dTag("ALOGDFSU","1111111111111111111");
        Context context = getApplicationContext();
        // 获取当前包名
        String packageName = context.getPackageName();
        // 获取当前进程名
        String processName = getProcessName(android.os.Process.myPid());
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        /**
         * 注册时申请的APPID:9da8325b03
         * APPID不允许随便修改，否则苏登福会打死你的
         * 第三个参数为SDK调试模式开关，调试模式的行为特性如下：
         * 输出详细的Bugly SDK的Log；
         * 每一条Crash都会被立即上报；
         * 自定义日志将会在Logcat中输出。
         * 建议在测试阶段建议设置成true，发布时设置为false。
         */
        if (!isRelease) {//本地调试版本：Rchat_dev
            CrashReport.initCrashReport(getApplicationContext(), "fe4501e83c", true);
        } else { //正式版本：Rchat
            CrashReport.initCrashReport(getApplicationContext(), "9da8325b03", false);
        }
//        CrashReport.testJavaCrash();
    }

    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    private void initAirtalkee() {
        //Airtalkee初始化设置
        AirtalkeeAccount.getInstance().AirTalkeeConfig(this, AppConfig.SERVER_ADDRESS, AppConfig.SERVER_PORT, true);
        //设置SDK Log 开关
        AirtalkeeAccount.getInstance().AirTalkeeConfigTrace(AppConfig.TRACE_MODE);
        //开启或关闭实时音频的本地录制
        PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().setSessionLocalRecordEnable(AppConfig.SESSION_LOCAL_RECORD_ENABLE);
        //SDK省电处理
        AirtalkeeAccount.getInstance().AirTalkeePowerManagerRun(this);
        AirtalkeeAccount.getInstance().AirTalkeeTimerApiRun(this);
    }


    public static Context getContext() {
        return mContext;
    }

    public static PocApplication getInstance() {
        return instance;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    public static Intent getExplicitIntent(Context context, Intent implicitIntent) {
        // Retrieve all services that can match the given intent
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);
        // Make sure only one match was found
        if (resolveInfo == null || resolveInfo.size() != 1) {
            return null;
        }
        // Get component info and create ComponentName
        ResolveInfo serviceInfo = resolveInfo.get(0);
        String packageName = serviceInfo.serviceInfo.packageName;
        String className = serviceInfo.serviceInfo.name;
        ComponentName component = new ComponentName(packageName, className);
        // Create a new intent. Use the old one for extras and such reuse
        Intent explicitIntent = new Intent(implicitIntent);
        // Set the component to be explicit
        explicitIntent.setComponent(component);
        return explicitIntent;
    }

    /**
     * 获取蓝牙连接状态
     *
     * @return
     */
    public int getConnectionState() {
        int flag = -1;

        //蓝牙适配器是否存在，即是否发生了错误
        if (btAdapter == null) {
            flag = -1;     //error
        } else if (btAdapter.isEnabled()) {
            int headset = btAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);        //蓝牙头戴式耳机，支持语音输入输出

            //查看是否蓝牙是否连接到三种设备的一种，以此来判断是否处于连接状态还是打开并没有连接的状态
            if (headset == BluetoothProfile.STATE_CONNECTED) {
                flag = headset;
            }
        }
        return flag;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }


    public void initNetworkListener() {
        NetworkReceiver.getInstance().setNetworkChangeListener(this);
    }

    @Override
    public void networkState(NetworkReceiver.NetworkState networkCode) {
        switch (networkCode) {
            case NETWORK_NO:
//                Toast.makeText(this, "没有网络连接", Toast.LENGTH_SHORT).show();
//                PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().setHeartBeat(60,0);
                break;
            case NETWORK_2G:
//                Toast.makeText(this, "2g网络", Toast.LENGTH_SHORT).show();
                PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().setHeartBeat(5, 0);
                break;
            case NETWORK_3G:
//                Toast.makeText(this, "3g网络", Toast.LENGTH_SHORT).show();
                PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().setHeartBeat(5, 0);
                break;
            case NETWORK_4G:
//                Toast.makeText(this, "4g网络", Toast.LENGTH_SHORT).show();
                PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().setHeartBeat(15, 0);
                break;
            case NETWORK_WIFI:
//                Toast.makeText(this, "WIFI网络", Toast.LENGTH_SHORT).show();
                PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().setHeartBeat(5, 0);
                break;
            case NETWORK_UNKNOWN:
//                Toast.makeText(this, "未知网络", Toast.LENGTH_SHORT).show();
//                PocAirtalkeeSessionManager.getPocAirtalkeeSessionManagerInstance().setHeartBeat(60,0);
                break;
            default:
//                Toast.makeText(this, "不知道什么情况", Toast.LENGTH_SHORT).show();
        }

//        Toast.makeText(this,networkCode + "",Toast.LENGTH_SHORT).show();
    }

}
